function formatDate(date, fmt) {
  if (!date) {
    return "";
  }
  if (typeof date === "number") {
    date = new Date(date);
  }
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
}
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  handleAddClick() {
    const inV = window.prompt("请输入数量");
    const time = Date.now();
    if (~~inV) {
      window.localStorage.setItem(
        "pu_" + time,
        JSON.stringify({ v: ~~inV, t: time })
      );
      this.setState({
        count: 0
      });
    }
  }

  handleRemoveAllClick() {
    if (window.confirm("确认要清空？")) {
      Object.entries(window.localStorage.valueOf())
        .filter(item => item[0].indexOf("pu_") === 0)
        .map(item => {
          window.localStorage.removeItem(item[0]);
        });
      this.setState({
        count: 0
      });
    }
  }

  handleItemRemoveClick(key) {
    window.localStorage.removeItem(key);
    this.setState({
      count: 0
    });
  }

  render() {
    let c = 0;
    Object.entries(window.localStorage.valueOf())
      .filter(item => item[0].indexOf("pu_") === 0)
      .map(item => {
        c += JSON.parse(item[1])["v"];
      });

    this.state.count !== c &&
      this.setState({
        count: c
      });

    return (
      <div className="app">
        <div className="count">
          <button onClick={() => this.handleRemoveAllClick()}>清空</button>
          <div>
            共<span>{this.state.count}</span>个
          </div>
          <button onClick={() => this.handleAddClick()}>添加</button>
        </div>
        <div className="items">
          {Object.entries(window.localStorage.valueOf())
            .filter(item => item[0].indexOf("pu_") === 0)
            .map(item => ({ ...JSON.parse(item[1]), key: item[0] }))
            .map(item => (
              <div className="item">
                <button onClick={() => this.handleItemRemoveClick(item.key)}>
                  x
                </button>
                <span>{item.v}</span>
                <span>{formatDate(item.t, "hh:mm")}</span>
              </div>
            ))}
        </div>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
